package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.*;
import model.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-12-17
 * Time: 17:45
 */
@WebServlet("/blog")
public class Blog extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        String blogId = req.getParameter("blogId");
        if(blogId == null){
            resp.setContentType("application/json;charset=utf-8");
            //不存在blogId这个参数, 获取微博列表
            req.setCharacterEncoding("utf8");
            //1. 获取到用户的登录状态
            HttpSession session = req.getSession(false);
            if(session == null){
                resp.setStatus(403);
                return;
            }
            User cur = (User) session.getAttribute("user");
            if(cur == null){
                resp.setStatus(403);
                return;
            }
            int id = cur.getUserid();

            UserConnect userConnect = HashPromulgatorToReceiver.userConnects[id];
            MicroBlogConnect node = HashIdToArticle.microBlogConnects[id];
            MyArrayList myArrayList = new MyArrayList();
            while(node != null){
                myArrayList.add(node.blog);
//                if(res.equals("[")){
//                    res += "{\"title\":\"" + node.blog.getTitle() +
//                            "\",\"username\":\"" + node.blog.getUsername() +
//                            "\",\"content\":\"" + node.blog.getContent() +
//                            "\",\"userId\":" + node.blog.getUserId() + "}";
//                }else{
//                    res += ",{\"title\":\"" + node.blog.getTitle() +
//                            "\",\"username\":\"" + node.blog.getUsername() +
//                            "\",\"content\":\"" + node.blog.getContent() +
//                            "\",\"userId\":" + node.blog.getUserId() + "}";
//                }
                node = node.next;
            }

            while(userConnect != null){
                MicroBlogConnect microBlogConnect = HashIdToArticle.microBlogConnects[userConnect.user.getUserid()];
                while(microBlogConnect != null){
                    myArrayList.add(microBlogConnect.blog);
//                    res += ",{\"title\":\"" + node.blog.getTitle() +
//                            "\",\"username\":\"" + node.blog.getUsername() +
//                            "\",\"content\":\"" + node.blog.getContent() +
//                            "\",\"userId\":" + node.blog.getUserId() + "}";
                    microBlogConnect = microBlogConnect.next;
                }
                userConnect = userConnect.next;
            }

            myArrayList.sort();

            String res = "[";

            for(int i = myArrayList.size() - 1; i >= 0; i--){
                if(!res.equals("[")){
                    res += ",";
                }
                res += "{\"title\":\"" + myArrayList.elem[i].getTitle() +
                        "\",\"username\":\"" + myArrayList.elem[i].getUsername() +
                        "\",\"content\":\"" + myArrayList.elem[i].getContent() +
                        "\",\"blogId\":" + myArrayList.elem[i].getBlogId() + "}";
            }

            res += "]";

            //[{"title":"111","content":"111","userId":5402693}]
            System.out.println(res);
            resp.getWriter().write(res);
        }else{
            HashIdToArticle hashIdToArticle = new HashIdToArticle();
            MicroBlog microBlog = hashIdToArticle.selectOne(Integer.parseInt(blogId));
//            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            String jsonString = objectMapper.writeValueAsString(microBlog);
            System.out.println(jsonString);
            resp.getWriter().write(jsonString);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        //1. 获取到用户的登录状态
        HttpSession session = req.getSession(false);
        if(session == null){
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            resp.setStatus(403);
            return;
        }
        //2.读取请求的内容
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || title.equals("") || content == null || content.equals("")){
            resp.setStatus(400);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("请求中的标题或正文不完整");
            return;
        }
        //3. 构造MicroBlog对象, 并插入到哈希表中
        int id = user.getUserid();
        MicroBlog microBlog = new MicroBlog();
        microBlog.setTitle(title);
        microBlog.setContent(content);
        microBlog.setUserId(id);
        microBlog.setUsername(UserInfo.users[id].getUsername());
        microBlog.setBlogId();
        HashBlogIdToBlog hashBlogIdToBlog = new HashBlogIdToBlog();
        hashBlogIdToBlog.add(microBlog);
        HashIdToArticle hashIdToArticle = new HashIdToArticle();
        hashIdToArticle.insert(id, microBlog);
        //4. 插入成功之后, 跳转到微博列表页
        resp.sendRedirect("microblog_list.html");
    }
}
